#include "ringQueue.h"
#include <stdlib.h>

system_error_code_t ring_queue_init(ring_queue_t *queue, int capacity, int set_size)
{
    // 参数检查
    if (queue == NULL || capacity <= 0 || set_size <= 0)
    {
        return SYSTEM_ERR_INVALID_ARGUMENT;
    }

    // 分配哈希集合数组
    queue->set = (hash_set_t *)malloc(sizeof(hash_set_t) * capacity);
    if (queue->set == NULL)
    {
        return SYSTEM_ERR_OUT_OF_MEMORY;
    }

    // 初始化每个哈希集合
    for (int i = 0; i < capacity; i++)
    {
        system_error_code_t ret = hash_set_init(&queue->set[i], set_size);
        if (ret != SYSTEM_ERR_OK)
        {
            // 初始化失败，释放已分配的内存
            for (int j = 0; j < i; j++)
            {
                hash_set_clear(&queue->set[j]);
            }
            free(queue->set);
            return ret;
        }
    }

    // 设置容量和初始索引
    queue->capacity = capacity;
    queue->current_index = 0;

    return SYSTEM_ERR_OK;
}

system_error_code_t ring_enqueue(ring_queue_t *queue, int fd, int *index)
{
    // 参数检查
    if (queue == NULL || index == NULL)
    {
        return SYSTEM_ERR_INVALID_ARGUMENT;
    }

    // 计算前一个索引位置
    int prev_index = (queue->current_index - 1 + queue->capacity) % queue->capacity;
    // 获取前一个哈希集合
    hash_set_t *prev_set = &queue->set[prev_index];
    // 向前一个哈希集合中添加文件描述符
    system_error_code_t ret = hash_set_put(prev_set, fd);
    if (ret != SYSTEM_ERR_OK && ret != SYSTEM_ERR_HASHMAP_ALREADY_EXISTS)
    {
        return ret; // 添加失败
    }

    *index = prev_index;

    return SYSTEM_ERR_OK; // 添加成功
}

system_error_code_t ring_dequeue_by_index(ring_queue_t *queue, int fd, int index)
{
    // 参数检查
    if (queue == NULL || index < 0 || index >= queue->capacity)
    {
        return SYSTEM_ERR_INVALID_ARGUMENT;
    }

    // 获取指定索引位置的哈希集合
    hash_set_t *set = &queue->set[index];
    return hash_set_remove(set, fd);
}